var common = {
    setSize: function () {
        var Dpr = 1, uAgent = window.navigator.userAgent;
        var isIOS = uAgent.match(/iphone/i);
        var wWidth = (screen.width > 0) ? (window.innerWidth >= screen.width || window.innerWidth == 0) ? screen.width : window.innerWidth : window.innerWidth, wDpr, wFsize;
        var wHeight = (screen.height > 0) ? (window.innerHeight >= screen.height || window.innerHeight == 0) ? screen.height : window.innerHeight : window.innerHeight;
        if (window.devicePixelRatio) {
            wDpr = window.devicePixelRatio;
        } else {
            wDpr = isIOS ? wWidth > 818 ? 3 : wWidth > 480 ? 2 : 1 : 1;
        }
        if (isIOS) {
            wWidth = screen.width;
            wHeight = screen.height;
        }
        if (wWidth > wHeight) {
            wWidth = wHeight;
        }
        wFsize = wWidth > 1080 ? 144 : wWidth / 7.5;
        wFsize = wFsize > 32 ? wFsize : 32;
        window.screenWidth_ = wWidth;
        document.querySelector('html').style.fontSize = wFsize + 'px';
//        document.getElementById("fixed").style.display="none";
    },
    init: function (type) {
        mui.init();
        if (type == "register-1") {
            this.register_1();
        } else if (type == "register-2") {
            this.register_2();
        } else if (type == "member") {
            this.member();
        }
    },
    phoneValid: {
        validPhoneCode: function () {
            var flag = false;
            var tel = document.querySelector('#tel').value;
            var code = document.querySelector('#code').value;
            $.ajax({
                type: "get",
                url: basePathUrl + "sms/check/code",
                data: {tel: tel, code: code},
                async: false,
                success: function (data) {
                    if (data.code == 1) {
                        flag = true;
                    }
                    else {
                        mui.toast(data.mem);
                    }
                }
            });
            return flag;
        },
        validCode: {
            time: 59,
            timeSatrt: null,
            onTime: function () {
                var validCode = common.phoneValid.validCode;
                if (validCode.time >= 0) {
                    var element = this;
                    validCode.elementBox.innerHTML = "重新发送(" + (validCode.time--) + ")";
                }
                else {
                    validCode.time = 59;
                    validCode.elementBox.innerHTML = '获取验证码';
                    clearInterval(validCode.timeSatrt);
                    common.code = true;
                }
            },

        },
        cookieSet: {
            init: function (codeBtn) {
                var validCode = common.phoneValid.validCode;
                validCode.elementBox = codeBtn;
                validCode.time = this.get();
                if (validCode.time > 0 && validCode.time < 59) {
                    common.code = false;
                    validCode.elementBox.innerHTML = "重新发送(" + (validCode.time--) + ")";
                    validCode.timeSatrt = setInterval(validCode.onTime, 1000);//1000为1秒钟
                }
                else {
                    validCode.time = 59;
                    common.code = true;
                }

            },
            set: function () {
                var time1 = "mobang=" + new Date().getTime();
                var objHours = 1;
                if (objHours > 0) {//为0时不设定过期时间，浏览器关闭时cookie自动消失
                    var date = new Date();
                    var ms = objHours * 60 * 1000;
                    date.setTime(date.getTime() + ms);
                    time1 += "; expires=" + date.toGMTString();
                }
                document.cookie = time1;

            },
            get: function () {
                var time_mo = new Date().getTime();
                var arrStr_mo = document.cookie.split("; ");
                var str_mo = 59;

                for (var i = 0; i < arrStr_mo.length; i++) {
                    var temp = arrStr_mo[i].split("=");
                    if (temp[0] == "mobang") {
                        str_mo = temp[1] - time_mo + 60000;
                        str_mo = parseInt(str_mo / 1000);
                        break;
                    }
                }
                return str_mo;
            }
        },
        seed: function () {
            var validCode = common.phoneValid.validCode;
            validCode.elementBox = this;
            var flag = validDate("#tel", {
                required: '手机号码不能为空',
                phone: '手机号码格式有误'
            });
            if (common.code && flag) {
                var tel = document.querySelector('#tel').value;
                common.code = false;
                $.ajax({
                    type: "get",
                    url: basePathUrl + "sendSMS?tel=" + tel,
                    async: true,
                    success: function (data) {
                        if (data.code == 1) {
                            mui.toast('验证码发送成功，请耐心等候');
                            validCode.timeSatrt = setInterval(validCode.onTime, 1000);//1000为1秒钟
                            common.phoneValid.cookieSet.set();
                        } else {
                            mui.toast(data.mem);
                            common.code = true;
                        }
                    }
                });
            }
        }
    },
    member: function () {
        mui('.status-types').on('tap', 'a', function () {
            var parent = this.parentNode;
            var children = parent.children;
            if (!this.classList.contains("active")) {
                var index = parseInt(this.getAttribute("data-index"));
		  		var active = common.transform(index);
				active.classList.remove('active');
				this.classList.add('active');
				$("#s_type").val(index);
            }
        });
        $(".location").on('tap', function () {
            var sign = this.getAttribute("bind");
            $(".location").next("div[data='" + sign + "']").toggle();
        });
    },
	transform : function(index){
		var width = document.querySelector('.check-data').clientWidth;
		var box = document.querySelector('.check-data-1');
		var active = document.querySelector('.active');
		box.style.transform = 'translate3d(-'+width*index+'px, 0px, 0px) translateZ(0px)';
		box.style.transitionTimingFunction = 'cubic-bezier(0.165, 0.84, 0.44, 1)';
		return active;
	},
    register_1: function () {
        var data = {};
        var init = this;
        mui.ready(function () {
            var cityPicker3 = cityInit();
            cityPicker3.setData(cityData3);
            var showCityPickerButton = document.getElementById('address1');
            var showStreetPickerButton = document.getElementById('address3');
            showCityPickerButton.addEventListener('tap', function (event) {
                cityPicker3.show(function (items) {
                    var a = null || '';
                    showCityPickerButton.value = items[0].text + " " + (items[1].text || '' ) + " " + (items[2].text || '') + " ";
                    var provinceCode = document.querySelector('#provinceCode');
                    if (provinceCode) {
                        document.querySelector('#provinceCode').value = items[0]['value'] || '';
                        document.querySelector('#cityCode').value = items[1]['value'] || '';
                        document.querySelector('#areaCode').value = items[2]['value'] || '';
                    }
                    showStreetPickerButton.value = '';
                    document.querySelector('#townCode').value = '';
                });
            }, false);

            var townPicker = townInit();
            showStreetPickerButton.addEventListener('tap', function (event) {
                var isTrue = setTown(townPicker);
                if (isTrue) {
                    townPicker.show(function (items) {
                        var a = null || '';
                        showStreetPickerButton.value = items[0].text || '';
                        document.querySelector('#townCode').value = items[0]['value'] || '';
                    });
                }

            }, false);

            var levelPicker = new mui.PopPicker({
                layer: 1
            });

            var levelCode = document.querySelector('#levelCode');
            if (levelCode.value != '') {
                levelPicker.pickers[0].list.angle = (parseInt(levelCode.value, 10) - 1) * 20;
            }
            levelPicker.setData([{text: '省级/直辖市', sort: 1}, {text: '市级', sort: 2}, {text: '区/县', sort: 3}]);
            var showLevelPickerButton = document.getElementById('level');
            showLevelPickerButton.addEventListener('tap', function (event) {
                levelPicker.show(function (items) {
                    var a = null || '';
                    showLevelPickerButton.value = items[0].text || '';
                    if (levelCode) {
                        document.querySelector('#levelCode').value = items[0]['sort'] || '';
                    }
                });
            }, false);
        });
        var elementBox = {
            submitBtn1: document.querySelector('.m-btn[steps="1"]'),
            submitBtn2: document.querySelector('.m-btn[steps="2"]'),
            window1: document.querySelector('#steps1'),
            window2: document.querySelector('#steps2')
        };
        var process = document.querySelectorAll('.flow-chart .process');

        var codeBtn = document.querySelector('.codeInput');
        this.phoneValid.cookieSet.init(codeBtn);
        init.code = true;
        codeBtn.addEventListener('click', common.phoneValid.seed);

        init.btn = true;
        elementBox['submitBtn1'].addEventListener('click', function () {
            var flag = validDate("#readname", {
                    required: '真实姓名不能为空'
                }) && validDate("#tel", {
                    required: '手机号码不能为空',
                    phone: '手机号码格式有误'
                }) && validDate("#address1", {
                    required: '所在地区不能为空'
                }) && validDate("#levelCode", {
                    required: '请选择服务商等级'
                });
            if (flag) {
                var index = layer.load(2, {shade: [0.2, '#393D49']});
                var callback = function (telIsRegistered, index) {
                    if (!telIsRegistered) {
                        mui.toast("该手机已经注册过服务商!");
                        layer.close(index);
                        return;
                    }
                    init.btn = false;
                    init.addData(data, ['readname', 'tel', 'address', 'sid', 'promotion_code', 'code']);
                    data.address = data.address;
                    data.province = $("#provinceCode").val();
                    data.city = $("#cityCode").val();
                    data.area = $("#areaCode").val();
                    data.town = $("#townCode").val();
                    data.level = $("#levelCode").val();
                    data.valBtn = $('.recommendBtn input[name="btn"]:checked').val();
                    apiWxServiceSave(data, elementBox, process, index);
                };
                ajaxWxVerifyTel($("#tel").val(), '5', callback, index);//校验该手机号是否注册过[服务商]用户
            }
            else {
                init.btn = true;
            }
        });
        mui('.recommendBtn').on('tap', 'div', function (event) {
            var value = this.getAttribute("btn");
            var box = $(".recommend .r-centent");
            var btn = document.querySelectorAll(".recommendBtn input");
            if (value == 'true') {
                btn[0].checked = true;
                box[0].classList.remove('hide');
                box[1].classList.add('hide');
            }
            else {
                btn[1].checked = true;
                box[0].classList.add('hide');
                box[1].classList.remove('hide');
            }
        });
    },
    register_2: function () {
        var data = {};
        var init = this;
        mui.ready(function () {
            var cityPicker3 = cityInit();
            cityPicker3.setData(cityData3);
            var showCityPickerButton = document.getElementById('address1');
            var showStreetPickerButton = document.getElementById('address3');
            showCityPickerButton.addEventListener('tap', function (event) {
                cityPicker3.show(function (items) {
                    var a = null || '';
                    showCityPickerButton.value = items[0].text + " " + ( items[1].text || '') + " " + (items[2].text || '') + " ";
                    var provinceCode = document.querySelector('#provinceCode');
                    if (provinceCode) {
                        document.querySelector('#provinceCode').value = items[0]['value'] || '';
                        document.querySelector('#cityCode').value = items[1]['value'] || '';
                        document.querySelector('#areaCode').value = items[2]['value'] || '';
                    }
                    showStreetPickerButton.value = '';
                    document.querySelector('#townCode').value = '';
                });
            }, false);

            var townPicker = townInit();
            showStreetPickerButton.addEventListener('tap', function (event) {
                var isTrue = setTown(townPicker);
                if (isTrue) {
                    townPicker.show(function (items) {
                        var a = null || '';
                        showStreetPickerButton.value = items[0].text || '';
                        document.querySelector('#townCode').value = items[0]['value'] || '';
                    });
                }

            }, false);
        });

        var elementBox = {
            submitBtn1: document.querySelector('.m-btn[steps="1"]'),
            submitBtn2: document.querySelector('.m-btn[steps="2"]'),
            submitBtn3: document.querySelector('.m-btn[steps="3"]'),
            window1: document.querySelector('#steps1'),
            window2: document.querySelector('#steps2'),
            window3: document.querySelector('#steps3')
        };
        var process = document.querySelectorAll('.flow-chart .process');

        var processEvent = function () {
            var parent = $(this).parent();
            var sign = parent.attr('data');
            if (sign != null) {
                $("div[id^=steps]").addClass('hide');
                $("#steps" + sign).removeClass('hide');
                parent.removeClass('active');
            }

            $(this).html(sign).unbind();


        };
        elementBox['submitBtn1'].addEventListener('click', function () {
            var flag = validDate("#readname", {
                    required: '真实姓名不能为空'
                }) && validDate("#tel", {
                    required: '手机号码不能为空',
                    phone: '手机号码格式有误'
                }) && validDate("#code", {
                    required: '短信验证码不能为空'
                }) && common.phoneValid.validPhoneCode();

            if (flag) {
                ajaxWxVerifyTel($("#tel").val(), '1');//校验该手机号是否注册过[维修店]用户
                if (!telIsRegistered) {
                    mui.toast("该手机已经注册过维修店用户!");
                    return;
                }
                init.addData(data, ['readname', 'tel']);
                elementBox.window1.classList.add('hide');
                elementBox.window2.classList.remove('hide');
                process[0].classList.add('active');
                $('.active span').html('&nbsp;').bind('click', processEvent);
            }
        });


        var codeBtn = document.querySelector('.codeInput');
        this.phoneValid.cookieSet.init(codeBtn);
        init.code = true;

        codeBtn.addEventListener('click', common.phoneValid.seed);

        init.btn = true;
        elementBox['submitBtn2'].addEventListener('click', function () {
            var flag = validDate("#cardno", {
                    required: '身份证号码不能为空'
                }) && validDate("#frontpath .fileValue", {
                    required: '请上传身份证正面'
                }) && validDate("#sidepath .fileValue", {
                    required: '请上传身份证反面'
                }) && validDate("#storename", {
                    required: '店铺名称不能为空'
                }) && validDate("#address1", {
                    required: '店铺地址不能为空'
                }) && validDate("#address2", {
                    required: '店铺地址填写不完整'
                }) && validDate("#contacts", {
                    required: '联系人不能为空'
                }) && validDate("#storeTel", {
                    required: '联系电话不能为空',
                    tel: '联系电话格式不合法'
                });
            if (flag && init.btn) {
                init.btn = false;
                init.addData(data, ['address', 'operator', 'regname', 'certpath', 'cardno', 'frontpath', 'sidepath', 'storename', 'address', 'contacts', 'storeTel', 'promotion_code', 'sid', 'audit_flag', 'code']);
                data.address = data.address;
                data.province = $("#provinceCode").val();
                data.city = $("#cityCode").val();
                data.area = $("#areaCode").val();
                data.town = $("#townCode").val();
                data.valBtn = $('.recommendBtn input[name="btn"]:checked').val();
                var index = layer.load(2, {shade: [0.2, '#393D49']});
                apiWxStoreSave(data, elementBox, process, index);
            } else {
                init.btn = true;
            }

        });
        mui('.recommendBtn').on('tap', 'div', function (event) {
            var value = this.getAttribute("btn");
            var box = $(".recommend .r-centent");
            var btn = document.querySelectorAll(".recommendBtn input");
            if (value == 'true') {
                btn[0].checked = true;
                box[0].classList.remove('hide');
                box[1].classList.add('hide');
            }
            else {
                btn[1].checked = true;
                box[0].classList.add('hide');
                box[1].classList.remove('hide');
            }
        });
    },
    addData: function (a, ids) {
        for (var i = 0; i < ids.length; i++) {
            var obj = document.querySelector('input[name="' + ids[i] + '"]');
            if (obj != null) {
                a[ids[i]] = obj.value;
            }
        }
    }
};

